<?php

namespace app\api\controller;

use app\api\model\Follow;
use app\api\model\FriendRequest;
use app\common\LogService;
use think\cache\driver\Redis;
use think\facade\Db;
use think\facade\Log;

class Friend extends Base
{
    // 申请添加好友
    public function sendRequest($id, $msg)
    {
        $recordLog = function ($status, $message = '') use ($id) {
            LogService::record(
                name: '添加好友',
                user_id: getUid(),
                target_id: $id,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
            );
        };
        if ($id == $this->uid) {
            $recordLog(0,'无法添加自己为好友');
            return error('无法添加自己为好友');
        }

        $hasUser = Db::name('user')->where(['id' => $id])->find();
        if (!$hasUser) {
            $recordLog(0,'用户不存在');
            return error('用户不存在');
        }

        $isFriend = Db::name('follow')
            ->where([
                ['user_id', '=', $this->uid],
                ['follow_id', '=', $id],
                ['relation_type', '=', 2]
            ])
            ->whereOr([
                ['user_id', '=', $id],
                ['follow_id', '=', $this->uid],
                ['relation_type', '=', 2]
            ])
            ->find();

        if ($isFriend) {
            $recordLog(0,'你们已经是好友了');
            return error('你们已经是好友了');
        }

        $exist = Db::name('friend_request')
            ->where('sender_id', $this->uid)
            ->where('receiver_id', $id)
            ->where('status', 0)
            ->find();

        if ($exist) {
            return error('已有待处理请求,请等待对方验证');
        }

        $data = [
            'sender_id' => $this->uid,
            'receiver_id' => $id,
            'message' => $msg ?: '久仰大名，能加个好友交流下吗？',
            'create_time' => time()
        ];

        $requestId = Db::name('friend_request')->insertGetId($data);
        $recordLog(1);
        return success();
    }
    // 待处理消息
    public function list()
    {
        $list = FriendRequest::with(['userInfo' => function ($query) {
            $query->field('id,nickname,avator');
        }])->where(['receiver_id' => $this->uid, 'status' => 0])->paginate();
        return success($list);
    }
    // 处理好友申请
    public function handleRequest($id)
    {
        $requestId = $id;
        $status = input('status', 1); // 1同意 2拒绝
        $exist = Db::name('friend_request')->where(['id' => $requestId, 'status' => 0, 'receiver_id' => $this->uid])->find();
        if (!$exist) return error('该请求已处理或不存在');

        Db::startTrans();
        try {
            // 更新请求状态
            Db::name('friend_request')
                ->where(['id' => $requestId])
                ->update(['status' => $status]);

            if ($status == 1) {
                // 获取双方用户ID
                $request = Db::name('friend_request')->find($requestId);
                $sender_id = $request['sender_id'];
                $receiver_id = $request['receiver_id'];
                $time = time();

                // 检查并处理发送者的关系记录
                $senderRelation = Db::name('follow')
                    ->where([
                        ['user_id', '=', $sender_id],
                        ['follow_id', '=', $receiver_id],
                        ['relation_type', '=', 2]
                    ])
                    ->find();

                if ($senderRelation) {
                    // 如果存在记录(包括软删除的),则更新
                    Db::name('follow')
                        ->where([
                            ['user_id', '=', $sender_id],
                            ['follow_id', '=', $receiver_id],
                            ['relation_type', '=', 2]
                        ])
                        ->update([
                            'delete_time' => 0,
                            'create_time' => $time
                        ]);
                } else {
                    // 不存在则新增
                    Db::name('follow')->insert([
                        'user_id' => $sender_id,
                        'follow_id' => $receiver_id,
                        'relation_type' => 2,
                        'create_time' => $time
                    ]);
                }

                // 检查并处理接收者的关系记录
                $receiverRelation = Db::name('follow')
                    ->where([
                        ['user_id', '=', $receiver_id],
                        ['follow_id', '=', $sender_id],
                        ['relation_type', '=', 2]
                    ])
                    ->find();

                if ($receiverRelation) {
                    // 如果存在记录(包括软删除的),则更新
                    Db::name('follow')
                        ->where([
                            ['user_id', '=', $receiver_id],
                            ['follow_id', '=', $sender_id],
                            ['relation_type', '=', 2]
                        ])
                        ->update([
                            'delete_time' => 0,
                            'create_time' => $time
                        ]);
                } else {
                    // 不存在则新增
                    Db::name('follow')->insert([
                        'user_id' => $receiver_id,
                        'follow_id' => $sender_id,
                        'relation_type' => 2,
                        'create_time' => $time
                    ]);
                }
            }

            Db::commit();
            LogService::record(
                user_id: getUid(),
                name: '处理好友请求',
                target_id: $id
            );
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return error();
        }
    }

    // 获取好友列表

    public function getFriends()
    {
        // 设置在线判断时间阈值（比如15分钟内算在线）
        $onlineThreshold = 900; // 15分钟 = 900秒
        $currentTime = time();

        $list = Follow::alias('f1')
            ->join('follow f2', 'f1.follow_id = f2.user_id AND f1.user_id = f2.follow_id')
            ->join('user u', 'f1.follow_id = u.id')
            ->where([
                ['f1.user_id', '=', $this->uid],
                ['f1.relation_type', '=', 2],
                ['f1.delete_time', '=', '0'],
                ['f2.relation_type', '=', 2],
                ['f2.delete_time', '=', '0']
            ])
            ->field('u.id,avator,nickname,f1.create_time,u.last_time')
            ->paginate();

        // 处理每个好友的在线状态和最后在线时间
        $friendsList = $list->getCollection()->map(function ($item) use ($currentTime, $onlineThreshold) {
            $lastTime = $item['last_time'];

            // 判断在线状态
            $isOnline = ($currentTime - $lastTime) <= $onlineThreshold;
            $item['avator'] = addHost($item['avator']);
            // 格式化最后在线时间
            $formattedLastTime = formatMessageTime($lastTime);
            return array_merge($item->toArray(), [
                'is_online' => $isOnline,
                'last_active' => $formattedLastTime,
                'online_status' => $isOnline ? '在线' : "最后在线 {$formattedLastTime}"
            ]);
        });

        // 更新分页数据的记录集
        $list->setCollection($friendsList);

        return success($list);
    }

    // 删除好友
    public function del($id)
    {
        $friendId = $id;
        if (!$friendId) return error('参数错误');
        // 检查是否为好友关系
        $isFriend = Follow::alias('f1')
            ->whereExists(function ($query) use ($friendId) {
                $query->table('gn_follow')
                    ->alias('f2')
                    ->whereColumn('f2.user_id', 'f1.follow_id')
                    ->whereColumn('f2.follow_id', 'f1.user_id')
                    ->where('f2.relation_type', 2)
                    ->where('f2.delete_time', 0);
            })
            ->where([
                ['f1.user_id', '=', $this->uid],
                ['f1.follow_id', '=', $friendId],
                ['f1.relation_type', '=', 2],
                ['f1.delete_time', '=', 0]
            ])
            ->find();

        if (!$isFriend) {
            return error('该用户不是您的好友');
        }
        LogService::record(
            user_id: getUid(),
            name: '删除好友',
            target_id: $id
        );
        Db::startTrans();
        try {
            // 软删除双向好友关系
            $time = time();
            Db::name('follow')
                ->where([
                    ['user_id', '=', $this->uid],
                    ['follow_id', '=', $friendId],
                    ['relation_type', '=', 2]
                ])
                ->update(['delete_time' => $time]);

            Db::name('follow')
                ->where([
                    ['user_id', '=', $friendId],
                    ['follow_id', '=', $this->uid],
                    ['relation_type', '=', 2]
                ])
                ->update(['delete_time' => $time]);

            Db::commit();
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return error('删除失败');
        }
    }
    // 发送消息
    public function sendMessage($id, $content)
    {
        if (!$id || !$content) {
            return error('参数错误');
        }
        // 检查是否互为好友
        $isFriend = Follow::checkIsFriend($id);
        if (!$isFriend) {
            return error('对方不是您的好友,无法发送消息');
        }
        $limitCheck = $this->checkMessageLimit();
        if (!$limitCheck['status']) {
            return error($limitCheck['msg']);
        }
        // 发送消息
        $data = [
            'sender_id' => $this->uid,
            'receiver_id' => $id,
            'content' => $content,
            'create_time' => time()
        ];
        LogService::record(
            user_id: getUid(),
            name: '好友间发送消息',
            target_id: $id
        );
        try {
            $res = Db::name('chatMessage')->insert($data);
            return success();
        } catch (\Exception $e) {
            return error('发送失败');
        }
    }
    // 消息发送限制
    public function checkMessageLimit()
    {
        $userId = $this->uid;
        $redisKey = "msg_limit:{$userId}:" . date('YmdHi');

        try {
            // 使用 Cache 门面操作 Redis
            $cache = \think\facade\Cache::store('redis');

            // 获取当前计数
            $count = $cache->get($redisKey, 0);
            $count++;

            // 设置新的计数和过期时间
            $cache->set($redisKey, $count, 60);  // 60秒过期

            // 检查频率限制
            if ($count > 30) {
                $ttl = 60 - (time() - strtotime(date('YmdHi') . '00'));
                return [
                    'status' => false,
                    'msg' => "发送过于频繁，请 {$ttl} 秒后重试",
                    'wait_seconds' => $ttl
                ];
            }

            return ['status' => true];
        } catch (\Exception $e) {
            \think\facade\Log::error('消息频率限制检查异常: ' . $e->getMessage());
            return ['status' => true];
        }
    }
    // 好友间列表
    public function getMessageList($id)
    {
        if (!$id) {
            return error('参数错误');
        }

        // 检查是否为好友关系
        $isFriend = Follow::alias('f1')
            ->whereExists(function ($query) use ($id) {
                $query->table('gn_follow')
                    ->alias('f2')
                    ->whereColumn('f2.user_id', 'f1.follow_id')
                    ->whereColumn('f2.follow_id', 'f1.user_id')
                    ->where('f2.relation_type', 2)
                    ->where('f2.delete_time', 0);
            })
            ->where([
                ['f1.user_id', '=', $this->uid],
                ['f1.follow_id', '=', $id],
                ['f1.relation_type', '=', 2],
                ['f1.delete_time', '=', 0]
            ])
            ->find();

        if (!$isFriend) {
            return error('该用户不是您的好友');
        }

        // 获取聊天记录
        $messages = Db::name('chatMessage')
            ->alias('m')
            ->join('user u1', 'u1.id = m.sender_id')
            ->join('user u2', 'u2.id = m.receiver_id')
            ->where([
                ['m.sender_id', 'in', [$this->uid, $id]],
                ['m.receiver_id', 'in', [$this->uid, $id]]
            ])
            ->field([
                'm.*',
                'u1.nickname as sender_name',
                'u1.avator as sender_avatar',
                'u2.nickname as receiver_name',
                'u2.avator as receiver_avatar'
            ])
            ->order('m.create_time desc')
            ->paginate(20);

        // 格式化消息时间
        $list = $messages->each(function ($item) {
            $item['create_time'] = formatMessageTime($item['create_time']);
            return $item;
        });

        return success($list);
    }
}
